package com.dingpeikeji.quickdeer.modules.rentproduct.web;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.CacheUtils;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.cupons.entity.CuponsInfo;
import com.dingpeikeji.quickdeer.core.modules.cupons.service.TCuponsService;
import com.dingpeikeji.quickdeer.core.modules.line.entity.TLine;
import com.dingpeikeji.quickdeer.core.modules.line.service.TLineService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.mobile.service.OrderService;
import com.dingpeikeji.quickdeer.mobile.web.MobileJsonController;
import com.dingpeikeji.quickdeer.modules.base.service.FrontUserService;
import com.dingpeikeji.quickdeer.modules.base.web.FSysController;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ProRentOrders;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.ShareRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TDemands;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentgroup;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TRentproduct;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.FRentproductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.RentproductOrderService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.ShareProductService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentgroupService;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TRentproductService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateCodeTool;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.UUIDUtils;
import com.google.common.collect.Lists;

/**
 * 旅游拼车接口
 *
 */
@Controller
@RequestMapping(value = "/f/mobile")
public class ShareRentController extends BaseController {
	
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@Autowired
	private TRentproductService tRentproductService;
	@Autowired
	private TOrdersService ordersService;
	@Autowired
	private TSitedtlService tSitedtlService;
	@Autowired
	private TLineService lineService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private FRentproductService rentproductService;
	@Autowired
	private TRentgroupService tRentgroupService;
	@Autowired
	private TCuponsService tCuponsService;
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private ShareProductService shareProductService;
	@Autowired
	private RentproductOrderService rentproductOrderService;
	@Autowired
	private TOrdersService tOrdersService;
	@Autowired
	private TCuponsService cuponsService;

	/**
	 *AA拼车生成产品
	 */
	@RequestMapping(value = "genShareProduct")
	@ResponseBody
	public BackResult list(String cuponsId,String rentid,String fromdate,String boardaddr,String userid, 
			HttpServletRequest request,String enddate,String minamount,String payertel,String contacts) {
		User user = frontUserService.get(request.getParameter("userid"));
		Map<String, Object> map = new HashMap<String, Object>();
		if (user==null) {
			return BackResult.build("400", "获取用户信息失败");
		}
		Date fromDate = DateUtils.parseDate(fromdate);
		Date endDate = DateUtils.parseDate(enddate);
		if (fromDate.before(endDate)) {
			return BackResult.build("400", "截止时间不能小于出发时间");
		}
		TRentproduct rentproduct = tRentproductService.get(rentid);
		//获取rentgroup
		TRentgroup rentgroup = tRentgroupService.get(rentproduct.getRentgrpid());
		//校验拼车总人数和车型核载人数
		if (Integer.parseInt(minamount) > rentproduct.getCargotype().getSeats()) {
			return BackResult.build("400", "拼车人数不能超过车辆核载人数");
		}
		if (TRentgroup.RENT_TYPE_DAY.equals(rentgroup.getRenttype())) {
			return BackResult.build("400", "不支持此类型拼车");
		}
		// 获取产品实时价格
		if (rentproduct != null) {
			// 协议价逻辑处理
			TRentproduct query = new TRentproduct();
			query.setRentid(rentproduct.getRentid());
			query.setDepartdate(DateUtils.parseDate(fromdate));
			// 如果是未登录或者是普通用户身份（非企业用户）则只可查看面向公众的整车
			rentproductService.setCompAgreerateOffice(query, request, "f");
			query = rentproductService.getSuitrtnprice(query);
			rentproduct.setSuitrtnprice(query.getSuitrtnprice());
		}
		//获取优惠券信息
		//计算价格
		double realPrice = 0;
		ShareRentproduct shareRentproduct = new ShareRentproduct();
		CuponsInfo cuponsInfo = new CuponsInfo();
		if (StringUtils.isNotEmpty(cuponsId)) {
			cuponsInfo = tCuponsService.getCuponsByRecordId(cuponsId);
			shareRentproduct.setUsecupons("1");
			shareRentproduct.setCuponsId(cuponsId);
			realPrice = rentproduct.getSuitrtnprice() - Double.parseDouble(cuponsInfo.getPrice());
		}else{
			realPrice = rentproduct.getSuitrtnprice();
		}
		//根据人数计算平均价格
		double avgPrice = Math.round(realPrice / Integer.parseInt(minamount));
		//初始化shareProduct
		shareRentproduct.setSid(UUIDUtils.getId().substring(0, 10));
		shareRentproduct.setOfficeId(rentgroup.getOffice().getId());
		shareRentproduct.setProductname(rentgroup.gettLine().getLinename()+rentgroup.getDaysnum()+"日拼车");
		shareRentproduct.setCreateBy(user);
		shareRentproduct.setCreateDate(new Date());
		shareRentproduct.setMaxamount(rentproduct.getCargotype().getSeats()+"");
		shareRentproduct.setMinamount(minamount);
		shareRentproduct.setDaysnum(rentgroup.getDaysnum()+"");
		shareRentproduct.setRentgrpid(rentgroup.getRentgrpid()+"");
		shareRentproduct.setRentid(rentid);
		shareRentproduct.setCargotype(rentproduct.getCargotype().getCargotypeid()+"");
		shareRentproduct.setPurchasenum("1");//拼车只能为1
		shareRentproduct.setFromdate(fromDate);
		shareRentproduct.setEnddate(endDate);
		shareRentproduct.setBoardaddr(boardaddr);
		shareRentproduct.setPhone(payertel);
		shareRentproduct.setContacts(contacts);
		shareRentproduct.setAvgprice(avgPrice);
		shareRentproduct.setCurrentsell(0);//初始化已购买人数
		shareRentproduct.setTotalprice(realPrice);//使用优惠券之后的价格
		shareRentproduct.setStatus("0");
		shareRentproduct.setSharetype(ShareRentproduct.SHARE_TYPE_TRAVEL);
		shareRentproduct.setDepartsite(rentgroup.getDepartcity().getSiteid());
		shareRentproduct.setDestsite(rentgroup.getDestcity().getSiteid());
		String linepic = shareProductService.getLinePic(rentgroup.getRentgrpid());
		shareRentproduct.setLinepic(linepic);
		//插入数据
		int result = shareProductService.insert(shareRentproduct);
		if (result > 0) {
			map.put("sid", shareRentproduct.getSid());
			map.put("sharetype", shareRentproduct.getSharetype());
			map.put("avgprice", shareRentproduct.getAvgprice());
			map.put("productname", shareRentproduct.getProductname());
			map.put("linepic", shareRentproduct.getLinepic());
			return BackResult.ok(map);
		}else{
			return BackResult.build("400", "生成拼车失败");
		}
	}
	@RequestMapping("shareBooking")
	@ResponseBody
	public BackResult booking(String sid,String userid,TOrders tOrders,String cuponsId,String contacts,String payertel,Integer paycount ) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		User user = frontUserService.get(userid);
		if (user==null) {
			return BackResult.build("400", "获取用户信息失败");
		}
		//获取拼车产品信息
		ShareRentproduct shareRentproduct = shareProductService.getInfo(sid);
		if (shareRentproduct==null ) {
			return BackResult.build("400", "获取拼车产品失败");
		}
		//同一个拼车产品,如果用户已经购买但是没有付款,不让他继续购买
		List<String> orderids = tOrdersService.checkIsCart(sid,userid);
		if (orderids.size()>0) {
			return BackResult.build("400", "你有未支付的拼车订单,请支付完成后再次下单");
		}
		//购买数量>最大可购买数量(拼团人数-已购买数量)
		int maxCartCount = Integer.parseInt(shareRentproduct.getMinamount()) - shareRentproduct.getCurrentsell();
		if (paycount> maxCartCount || paycount <=0) {
			return BackResult.build("400", "当前订单最多可拼车人数:"+maxCartCount+"");
		}
		//计算支付金额
		double dueamount = Math.ceil(paycount * shareRentproduct.getAvgprice());
		CuponsInfo cuponsInfo = new CuponsInfo();
		//使用了优惠券
		if (StringUtils.isNotEmpty(cuponsId)) {
			cuponsInfo = tCuponsService.getCuponsByRecordId(cuponsId);
			if (cuponsInfo==null) {
				return BackResult.build("400", "暂无优惠券信息");
			}
			dueamount = Math.ceil(dueamount - Double.parseDouble(cuponsInfo.getMoney()));
		}
		//初始化order
		tOrders.setOrdername(shareRentproduct.getProductname());
		//sharetype=旅游包车拼车
		if (ShareRentproduct.SHARE_TYPE_TRAVEL.equals(shareRentproduct.getSharetype())) {
			tOrders.setOrdertype(TOrders.ORDER_TYPE_TRAVEL_SHARE);
			tOrders.setRealscheid(shareRentproduct.getRentid());
		}else if (ShareRentproduct.SHARE_TYPE_AIR.equals(shareRentproduct.getSharetype())) {
			//sharetype=接送机拼车
			tOrders.setOrdertype(TOrders.ORDER_TYPE_AIR_SHARE);
			tOrders.setRealscheid(System.currentTimeMillis()+"");
		}
		tOrders.setCargotypeid(Integer.parseInt(shareRentproduct.getCargotype()));
		tOrders.setOfficeids(shareRentproduct.getOfficeId());
		tOrders.setBoardaddr(shareRentproduct.getBoardaddr());
		tOrders.setBookingdays(Integer.parseInt(shareRentproduct.getDaysnum()));
		tOrders.setDepartdateStr(DateUtils.formatDateTime(shareRentproduct.getFromdate()));
		tOrders.setDueamount(dueamount+"");
		tOrders.setOrderuserid(userid);
		tOrders.setPurchasenum("1");//车辆数限定为1
		//查询订单表中是否已经有人购买该拼车订单
		List<TOrders> already = tOrdersService.getOrderByShareId(sid);
		if (already.size()>0) {
			tOrders.setBookingtype(TOrders.BOOKING_TYPE_NOT_FIRST_SHARE);//不是第一次生成拼车订单
			tOrders.setRealscheid(already.get(0).getRealscheid());
		}
		// 消息集合
		List<String> messages = Lists.newArrayList();
		if (messages.isEmpty()) {
			//生成订单
			ProRentOrders pro = null;
			try {
				pro = rentproductOrderService.genOrder(tOrders);
				if (pro.success()) { 
					Integer orderid = pro.getOrderid();
					//优惠券处理
					if(cuponsId!=null){
						cuponsInfo.setMoney(cuponsInfo.getPrice());
						cuponsInfo.setCuponsId(cuponsId);
						cuponsService.dealWithCupon(cuponsInfo, orderid+"", null);
						orderService.updateOrderUseCupon(orderid+"");
					}
					//添加身份证,拼车产品id
					tOrdersService.insertSFZ(tOrders.getSfzCode(),contacts,payertel,sid,paycount,orderid);
					map.put("orderid", orderid);
					map.put("dueamount",dueamount);
					map.put("ordername", tOrders.getOrdername());
					return BackResult.ok(map);
				}
				messages.add(pro.getReturnmsg());
			} catch (Exception e) {
				messages.add(e.getMessage());
			}
		}
		return BackResult.build("400", messages.get(0));
	}
	
	//拼车列表
	@RequestMapping(value = "shareList")
	@ResponseBody
	public BackResult getShareList(HttpServletRequest request,HttpServletResponse response,
			ShareRentproduct shareRentproduct,@RequestParam(value="pageNo",defaultValue="1")Integer pageNo,
			@RequestParam(value="pageSize",defaultValue="5")Integer pageSize,String time){
		List<String> boardlist =shareProductService.getBoardList(shareRentproduct);//上车地点
		//分页查询
		Page<ShareRentproduct> page = new Page<ShareRentproduct>(request, response);
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page = shareProductService.findPage(page, shareRentproduct);
		
		if(time!=null&&time.length()>0){
			String[] t=time.split(",");
			Date before=new Date();
			Date after=new Date();
			try {
			  before =df.parse(shareRentproduct.getFromdateStr()+" "+t[0]);
			  after =df.parse(shareRentproduct.getFromdateStr()+" "+t[1]);
			} catch (ParseException e) {
				e.printStackTrace();
				return BackResult.build("400", "时间转化出错");
			}
			for(int i=0;i<page.getList().size();i++){
				if(page.getList().get(i).getFromdate().before(before)||page.getList().get(i).getFromdate().after(after)){
					page.getList().remove(i);
					i--;
					page.setCount(page.getCount()-1);
				}
			}
		}
		
		if (page.getCount()==0) {
			return BackResult.build("400", "暂无有效拼车产品");
		}
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		if(shareRentproduct.getSharetype().equals("1")){
			List<String> day =shareProductService.getDayList(shareRentproduct);
			map.put("dayList", day);
		}
		map.put("boardList", boardlist);
		map.put("shareList", page.getList());
		map.put("totalCount", page.getCount());
		return BackResult.ok(map);
	}
	//查看拼车
	@RequestMapping(value = "getShareDetailById")
	@ResponseBody
	public BackResult getShareDetailById(HttpServletRequest request,HttpServletResponse response,String sid){
		Map<String, Object> map = new HashMap<String, Object>();
		ShareRentproduct shareRentproduct = shareProductService.getElseInfo(sid);
		if (shareRentproduct==null) {
			return BackResult.build("400", "查询产品信息失败");
		}
		if (shareRentproduct.getCurrentsell().equals(shareRentproduct.getMinamount())) {
			return BackResult.build("400", "参团人数已满,不可预订");
		}
		//处理线路描述
		if (ShareRentproduct.SHARE_TYPE_TRAVEL.equals(shareRentproduct.getSharetype())) {
			if (shareRentproduct.gettRentgroup()!=null) {
				String description = shareRentproduct.gettRentgroup().getDescription();
				description = description.replaceAll("&nbsp;", "");
				String[] arr = description.split("第"+"\\S"+"天");
				description = description.replaceAll("&nbsp;", "");
				Map<String, String> descriptions = new HashMap<String, String>();
				formatDesc(arr, descriptions);
				map.put("descriptions", descriptions);
			}
		}
		//计算该产品失效剩余时间
		Date afterDate = shareRentproduct.getEnddate();
		Date beforeDate = new Date();
		//时间差
		long distanceOfTwoDate = DateUtils.getDistanceMilesOfTwoDate(beforeDate, afterDate);
		String time = DateUtils.formatMileToTime(distanceOfTwoDate);
		if ("2".equals(shareRentproduct.getStatus())) {
			map.put("surplusTime", "报名截止");
		}else {
			map.put("surplusTime", "报名还剩"+time);
		}
		map.put("cartype", shareRentproduct.gettCargotype().getTypename());
		map.put("office", shareRentproduct.getOffice());
		map.put("shareProduct", shareRentproduct);
		map.put("createManImage", shareRentproduct.getUser().getUserimage());
		map.put("createManName", shareRentproduct.getUser().getName());
		if (ShareRentproduct.SHARE_TYPE_AIR.equals(shareRentproduct.getSharetype())) {
			map.put("shareFee", ShareRentproduct.SHARE_FEE_Air);
		}else{
			map.put("shareFee", ShareRentproduct.SHARE_FEE);
		}
		map.put("shareNotes", ShareRentproduct.SHARE_NOTES);
		String productname = shareRentproduct.getProductname();
		//春节拼车处理
		if(productname.contains("大学城")){
			productname = productname.substring(0,productname.length()-4);
			//获取线路描述
			TLine tLine = lineService.getLineByName(productname);
			String description = tLine.getDescription();
			description = description.replaceAll("&nbsp;", "");
			String[] arr = description.split("第"+"\\S"+"天");
			description = description.replaceAll("&nbsp;", "");
			Map<String, String> descriptions = new HashMap<String, String>();
			formatDesc(arr, descriptions);
			//霞客约车
			shareRentproduct.getOffice().setAbbr("霞客约车");
			shareRentproduct.getOffice().setName("霞客约车");
			map.put("descriptions", descriptions);
			map.put("createManName", "霞客约车");
			map.put("shareFee", null);
		}
		if(shareRentproduct.getSameid()!=null&&shareRentproduct.getSameid().length()>1){
			ShareRentproduct t =new ShareRentproduct();
			t.setSameid(shareRentproduct.getSameid());
			Page<ShareRentproduct> page = new Page<ShareRentproduct>(request, response);
			page.setPageSize(500);
			page = shareProductService.findPage(page, t);
			map.put("shareProductList", page.getList());
		}
		map.put("shareProduct", shareRentproduct);
		return BackResult.ok(map);
	}
	private List<Long> formatDesc(String[] arr, Map<String, String> map) {
		//el表达式中数字1是Long类型，无法匹配后台map中的int。
		//修改 map.put(0L, value);  前台 ：${map[1]}.
		List<Long> list = new ArrayList<Long>();
		long i = 1;
		for (String s : arr) {
			if (StringUtils.isEmpty(s)||s.length()==0||"".equals(s)) {
				continue;
			}
			//String substring = s.substring(1);
			map.put(i+"",s.replaceAll(" {2,}", ""));//X{n,} X，至少 n 次
			i++;
			list.add(i);
		}
		return list;
	}

	// 查看拼车
	@RequestMapping(value = "checkPayCountForIOS")
	@ResponseBody
	public BackResult checkPayCountForIOS(String orderid, String userid) {
		User user = frontUserService.get(userid);
		if (user == null) {
			return BackResult.build("400", "非法参数");
		}
		// 根据订单号查询金额
		TOrders tOrders = ordersService.get(orderid);
		if (!tOrders.getOrderuserid().equals(userid)) {
			return BackResult.build("400", "获取订单信息失败");
		}
		if (!TOrders.STATUS_NO_PAY.equals(tOrders.getOrderstatus())) {// 未支付状态才可以支付
			return BackResult.build("400", "该订单不可支付");
		}
		// AA拼车,支付的时候再次判断拼车产品剩余预订人数
		String shareid = tOrders.getShareid();
		ShareRentproduct shareRentproduct = shareProductService.getInfo(shareid);
		// 剩余可预订数量
		int maxCartCount = Integer.parseInt(shareRentproduct.getMinamount()) - shareRentproduct.getCurrentsell();
		if (tOrders.getPaycount() > maxCartCount) {
			return BackResult.build("400", "当前拼车最多可拼车人数:" + maxCartCount + ",请重新预定");
		}
		if (shareRentproduct.getEnddate().before(new Date())) {
			return BackResult.build("400", "产品已过期,请重新预定");
		}
		return BackResult.ok();
	}
	
	//拼车出发目的地下拉
		@RequestMapping(value = "directory")
		@ResponseBody
		public BackResult directory(HttpServletRequest request,HttpServletResponse response,ShareRentproduct sharetype){
			Map<String, Object> map = new HashMap<String, Object>();
			//出发地集合
			Set<Map<String, String>> departSet = new HashSet<Map<String,String>>();
			//获取出发地
			List<String> departList = shareProductService.getDepartList(sharetype);
			if (departList!=null&&departList.size()>0) {
				for (String sr : departList) {
					TSitedtl depart = tSitedtlService.get(sr);
					Map<String, String> departMap = new HashMap<String, String>();
					departMap.put("siteid", depart.getSiteid());
					departMap.put("sitename",depart.getSitename());
					departSet.add(departMap);
				}
			}
			//目的地集合
			Set<Map<String, String>> destSet = new HashSet<Map<String,String>>();
			List<String> destList = shareProductService.getDestList(sharetype);
			if (destList!=null&&destList.size()>0) {
				for (String sr : destList) {
					Map<String, String> destMap = new HashMap<String, String>();
					TSitedtl dest = tSitedtlService.get(sr);
					destMap.put("siteid", dest.getSiteid());
					destMap.put("sitename",dest.getSitename());
					destSet.add(destMap);
				}
			}
			map.put("departSet",departSet);
			map.put("destSet", destSet);
			return BackResult.ok(map);
		}
	
}




























